<?php

namespace common\service;

use common\model\ReviewFeedbackEntityModel;
use common\model\ReviewFeedbackModel;
use common\model\NoteEntityRelationModel;
use common\model\UserModel;
use support\SingletonTrait;

/**
 * 需求单服务层
 */
class ReviewFeedbackEntityService
{
    use SingletonTrait;

    private $reviewFeedbackEntityModel;
    private $noteEntityRelationModel;
    private $reviewFeedbackModel;

    public function __construct()
    {
        $this->reviewFeedbackEntityModel = model(ReviewFeedbackEntityModel::class);
        $this->noteEntityRelationModel = model(NoteEntityRelationModel::class);
        $this->reviewFeedbackModel = model(ReviewFeedbackModel::class);
    }

    /**
     * 获取需求信息
     * @author meilunzhi
     * @param    $entityId
     * @return array
     */
    public function getEntityIdByDemandOrderId($entityId)
    {
        $result = [];
        if(empty($entityId)){
            return $result;
        }
        $entityId = implode(',', $entityId);
        $where = [
            "entity_id" => ['in' , $entityId],
            "published" => 'yes',
        ];
        // 根据实体查找需求单review_feedback_id
        $reviewFeedbackIdList = $this->reviewFeedbackEntityModel
            ->distinct(true)
            ->field(['review_feedback_id'])
            ->where($where)
            ->select();

        if (empty($reviewFeedbackIdList)) {
            return $result;
        }

        $result['review_feedback_id'] = array_column( $reviewFeedbackIdList ,'review_feedback_id');
        return $result;
    }

    /**
     * 查找需求内容数据
     * @param $reviewFeedBackIds
     * @param $entityIds
     * @param $projectId
     * @param $stepCategoryId
     *
     * @return array
     */
    public function getFindReviewFeedbackContent($reviewFeedBackIds,$entityIds,$projectId,$stepCategoryId)
    {
        if(empty($reviewFeedBackIds) || empty($entityIds) || empty($projectId) || empty($stepCategoryId)){
            return [];
        }
        $field = [
            'note.id', 'note.proposer', 'note.proposer_department', 'note.text',
            'ner.step_category_id', 'ner.from_upstream_step_category_id',
            'note.review_feedback_id', 'ner.entity_id', 'ner.project_id',
        ];

        $where = [
            'ner.review_feedback_id' => is_array($reviewFeedBackIds) ? ['in', $reviewFeedBackIds] : $reviewFeedBackIds,
            'ner.entity_id'          => is_array($entityIds) ? ['in', $entityIds] : $entityIds,
            'ner.project_id'         => $projectId,
            'ner.step_category_id'   => $stepCategoryId,
            'ner.relation_type'      => 'step_category',
        ];

        // 查找需求内容数据
        $reviewFeedBackContentInfo = $this->noteEntityRelationModel
            ->alias('ner')
            ->field($field)
            ->join('note on note.id = ner.note_id','left')
            ->where($where)
            ->select();

        if(empty($reviewFeedBackContentInfo)){
            return [];
        }

        return $reviewFeedBackContentInfo;
    }

    /**
     * 获取需求数据
     * @author meilunzhi
     * @param $reviewFeedbackIds
     * @param $entityId
     * @param $stepCategoryId
     *
     * @return array
     */
    public function getReviewFeedBackList( $reviewFeedbackIds, $entityId, $stepCategoryId )
    {
        if(empty($reviewFeedbackIds) || empty($entityId) || empty($stepCategoryId)){
            return [];
        }
        //获取需求单指定段
        $field = [
            'rf.id as review_feedback_id', 'rf.title', 'rfe.entity_id',
            'rf.stage_id', 'ner.step_category_id', 'rfe.is_append',
            'rf.stage_name', 'rf.proposer', 'rf.proposer_department',
            'rfe.published', 'rfe.published_time',
        ];
        // 查找条件
        $where = [
            'rf.id' => ['in', $reviewFeedbackIds],
            'rfe.entity_id' => ['in', $entityId],
            'ner.step_category_id' => $stepCategoryId,
        ];
        // 返回需求相关内容信息
        $reviewFeedbackList = $this->reviewFeedbackModel
            ->distinct(true)
            ->alias('rf')
            ->join('note_entity_relation as ner on rf.id = ner.review_feedback_id','left')
            ->join('review_feedback_entity as rfe on rf.id = rfe.review_feedback_id','left')
            ->field($field)
            ->where($where)
            ->select();

        // 如果数据不存返回空
        if(empty($reviewFeedbackList)){
            return [];
        }

        // 获取需求的用户信息或部门信息
        $departmentIds = array_unique(array_column($reviewFeedbackList, 'proposer_department'));
        $proposerIds = array_unique(array_column($reviewFeedbackList, 'proposer'));
        // 获取需求提出人信息
        $userList = model(UserModel::class)
            ->where(['id' => ['in', implode(',', $proposerIds)]])
            ->field('id,name,union_id')
            ->select();

        if(!empty($userList)){
            $userList = array_column($userList, null, 'id');
            foreach ($reviewFeedbackList as  &$value) {
                $value['proposer_name'] = $userList[$value['proposer']]['name'] ?? '';
            }
        }
        // 获取提出人所在的组别信息
        if(!empty($departmentIds)){
            // 需求提出的所在组信息
            $departmentInfo = teamones_request('teamones-im',
                'department/get_department_list', [
                    'param' => [
                        'id' =>  $departmentIds,
                    ]
                ])['data'];
            // 需求提出的人信息
            if (!empty($departmentInfo)) {
                $departmentInfo = array_column($departmentInfo, null, 'id');
                foreach ($reviewFeedbackList as  &$value) {
                    $value['proposing_department_name'] = $departmentInfo[$value['proposer_department']]['name'] ?? '';
                }
            }
        }
        return $reviewFeedbackList;
    }


    /**
     * 需求单的原计划时间,和新的计划时间
     * @param  array  $reviewFeedBackIds
     * @param  int  $taskId
     * @return array
     */
    public function getOriginalNewPublished( $reviewFeedBackIds, $taskId)
    {
        if(empty($reviewFeedBackIds) || empty($taskId)){
            return [];
        }
        $field = [
            'rf.id as review_feedback_id', 'dot.type', 'dot.original_plan_time',
            'dot.task_id', 'dot.plan_delivery_time', 'dot.delay_time',
            'dot.delay_reason', 'dot.task_id',
        ];
        // 查询的条件 需求id 需求环节id delay_order_task type 类型为需求单 demand_order
        $where = [
            'rf.id' => ['in',$reviewFeedBackIds],
            'dot.task_id' => $taskId,
            'dot.type' => 'demand_order'
        ];
        // 根据需求单id 需求的环节id 查看需求的原计划发布时间，和新计划发布时间
        $reviewFeedBackTimeInfo = $this->reviewFeedbackModel
            ->alias('rf')
            ->join('delay_order_task as dot on rf.id = dot.link_id')
            ->field($field)
            ->where($where)
            ->select();

        // 如果没有数据返回空
        if(empty($reviewFeedBackTimeInfo)){
            return [];
        }

        return $reviewFeedBackTimeInfo;
    }
}
